from typing import Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from utils.mailUtils import EmailSender

router = APIRouter(
    prefix="/mail",
    tags=["mail"],
    responses={404: {"description": "Not found"}},
)


class EmailRequest(BaseModel):
    to_email: str        # 收件人邮箱
    subject: str         # 邮件主题
    body: str            # 邮件正文
    from_email: Optional[str] = None  # 发件人邮箱（可选）


@router.post("/send")
async def send_email(request: EmailRequest):
    """
    发送邮件的API端点
    
    参数:
        request: 包含邮件信息的请求对象
    
    返回:
        成功消息或HTTP异常
    """
    # 创建邮件发送器实例
    sender = EmailSender()
    # 调用发送邮件方法，传入请求中的邮件信息
    success = sender.send_email(
        to_email=request.to_email,  # 收件人邮箱
        subject=request.subject,    # 邮件主题
        body=request.body,          # 邮件正文内容
        from_email=request.from_email  # 发件人邮箱（如果提供）
    )
    
    # 检查邮件发送结果
    if not success:
        # 如果发送失败，抛出500错误
        raise HTTPException(status_code=500, detail="Email sending failed")
    # 发送成功，返回成功消息
    return {"message": "Email sent successfully"}